package com.yue.data.weather.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yue.data.weather.constant.Constant;
import com.yue.data.weather.service.IWeatherDataService;
import com.yue.data.weather.vo.WeatherResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author yuelinbo
 * @date 2018年07月25日 16:11
 * Copyright:2018-版权所有
 */
@Service
public class WeatherDataServiceImpl implements IWeatherDataService {

    Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = Constant.WEATHER_ID_URL + cityId;
        return this.doGetWeather(uri);
    }

    private WeatherResponse doGetWeather(String uri) {

        String strBody = null;
        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse response = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        //先查看缓存，缓存中有从缓存中取数据
        if (stringRedisTemplate.hasKey(uri)) {
            logger.info("Redis has data");
            strBody = ops.get(uri);
        } else {
            logger.info("Redis don't has data");
            throw new RuntimeException("Redis don't has data");
        }

        try {
            response = mapper.readValue(strBody,WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }
}
